package org.xinjiang.data.migration.flush.convert;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.xinjiang.data.migration.common.constant.CreateConstant;
import org.xinjiang.data.migration.common.mapstruct.CommonConvertConfig;
import org.xinjiang.data.migration.hainan.dto.res.CrimeNameResultDTO;
import org.xinjiang.data.migration.hainan.dto.res.DctBaseResultDTO;
import org.xinjiang.data.migration.hainan.dto.res.JzdxResultDTO;
import org.xinjiang.data.migration.hainan.entity.CrimeRelationshipsEntity;

import java.util.*;
import java.util.stream.Collectors;

@Mapper(config = CommonConvertConfig.class)
public abstract class CrimeRelationshipsFlushConvert {
    /**
     * 犯罪类型和具体罪名，数据库中存储的都是code
     *
     * @param s             JzdxResultDTO
     * @param crimeNameList crimeNameList
     * @return
     */
    public List<CrimeRelationshipsEntity> convert(JzdxResultDTO s, List<CrimeNameResultDTO> crimeNameList) {
        List<CrimeRelationshipsEntity> crimeRelationshipsEntityList = new ArrayList<>();

        String crimeName = s.getJtzm();
        if (StringUtils.isEmpty(crimeName)) {
            return crimeRelationshipsEntityList;
        }

        List<String> crimNameList = new ArrayList<>();

        if (crimeName.contains(",")) {
            List<String> subNameList = Arrays.stream(crimeName.split(",")).map(String::trim).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(subNameList)) {
                crimNameList.addAll(subNameList);
            }
        } else {
            crimNameList.add(crimeName);
        }

        Map<String, CrimeNameResultDTO> nameCodeMap = crimeNameList.stream().collect(Collectors.toMap(DctBaseResultDTO::getCode, v -> v, (v1, v2) -> v1));
        crimNameList.forEach(c -> {
            if (nameCodeMap.containsKey(c)) {
                CrimeRelationshipsEntity entity = new CrimeRelationshipsEntity();
                entity.setCorrectorId(s.getId());
                entity.setTypeCrime(nameCodeMap.get(c).getPCode());
                entity.setSpecificCharges(c);
                entity.setCreateBy(CreateConstant.SYSTEM);
                entity.setCreateTime(new Date());
                crimeRelationshipsEntityList.add(entity);
            }
        });

        return crimeRelationshipsEntityList;
    }
}
